<?php
/*
 * page to allow adding and removal of project tasks
*/
//check for a valid session
include("../inc_files/utils/checksession.php");
// Create connection
include("../inc_files/utils/dbconnection.php");
//query for project details
$query ="SELECT Company, StartDate, EndDate, FirstName, LastName, ProjectTitle, ProjectDescription, ProjectManager
		FROM projects, customers, staff WHERE ProjectID = ? AND projects.ProjectManager = staff.UserID
		AND customers.CustomerID = projects.CustomerID;";
if($stmt = $mysqli -> prepare($query))	{
	//bind the customerid to the query
	$stmt -> bind_param("s", $projectID);

	//sanitise the input data
	$projectID = $mysqli->real_escape_string(trim($_GET["projectid"]));

	//execute the query
	$result = $stmt -> execute();

	//store the results
	$stmt->store_result();

	//bind the results to variables
	$stmt -> bind_result($customer, $startDate, $endDate, $PMfirstName, $PMlastName, $projectTitle, $descripion, $projectManager);

	//actually fetch the results
	$stmt->fetch();

	//close the statement
	$stmt -> close();

}
//check to see if the user is allowed to edit this project i.e.
//are they administrators or the project manager, if not redirect them to the home page
if(($_SESSION['userRole']!='1') && ($_SESSION['userid'] != $projectManager))
{
	header("location: /f21na/home/home.php");
	exit();
}
//include the page header
include("../inc_files/ui/header.php");
?>
<script type="text/javascript" src="../scripts/async.js"></script>
<script type="text/javascript" src="../scripts/datepicker.js"></script>
<script type="text/javascript" src="../scripts/utils.js"></script>
<!--include the script to hide/reveal the new item row-->
<script type='text/javascript'>
//show/hide the new item row
function togglenewitem() {
	if (document.getElementById('newitemrow').className == 'datagrid hidenewitem') {
		document.getElementById('newitemrow').className = 'datagrid shownewitem';
	} else {
		document.getElementById('newitemrow').className = 'datagrid hidenewitem';
	}
}
//async refresh of tasks datagrid
function refreshgrid(taskid){
	var nochache = Math.floor(Math.random() * 10000);
	getasync('a_listtasks.php?projectid=<?php echo $projectID?>&nocache=' +
			 nochache + '&taskid=' + taskid,'datagrid', true);		
}
//async update or add tasks
function updatetask(){
	// validate the form
	if(validateForm())
	{
	// create a new task then refresh the data grid with new data
	postasync('a_updatetask.php','form',['title', 'startdate','enddate','budget','projectid','taskid','percentcomplete'],  false); 
	refreshgrid();
	}
	
}
//async deletion of tasks
function deletetask(taskid){
	// confirm deletion with user
	if(confirm("Are you sure you want to mark this task as deleted?"))
	{
	// delete task then refresh the data grid with new data
	postasync('a_deletetask.php','value','taskid='+taskid, false); 
	refreshgrid();
	}
	
}
//check the new task form fields are valid
function validateForm(){
	// reset the styles on the form fields to remove
	// any highlighted errors from previous submissions
	var tf=document.getElementById("tasksform");		
	for (var i=0;i<tf.length;i++)
	  {
		  if(tf.elements[i].className = "tberror") tf.elements[i].className = "tbnormal"
	  }

	// check form validation
	var valid = true;
	var errormessage = "This form is not valid. Please correct the following errors.\n";

	// regular expression for dates in dd/mm/yyyy format
	var datereg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;

	// check the title field

		if(document.getElementById('title').value.length < 1){
			valid=false;
			document.getElementById('title').className = "tberror";
			errormessage += "\nTitle field empty";
		}
	
	// check the start date filed for not valid format

		var startdate = document.getElementById('startdate').value
		if(!startdate.match(datereg)){
			valid=false;
			document.getElementById('startdate').className = "tberror";
			errormessage += "\nStart date not valid (dd/mm/yyyy)";
		}
	
     
	// check the end date filed for not valid format
		var enddate = document.getElementById('enddate').value
		if(!enddate.match(datereg)){
			valid=false;
			document.getElementById('enddate').className = "tberror";
			errormessage += "\nEnd date not valid (dd/mm/yyyy)";
		}
	
	
	// check start date is after end date

	if(startdate.match(datereg) && enddate.match(datereg)){
		if(checkStartEndDates(startdate,enddate)){
			valid=false;
			document.getElementById('enddate').className = "tberror";
			document.getElementById('startdate').className = "tberror";
			errormessage += "\nEnd date is earlier than start date.";
		}
		
	}
	  	
	// check the budget field is a positive iteger
	var budget = document.getElementById('budget').value
	if(!(budget.match('^[0-9]+[0-9]*$'))){
		valid=false;
		document.getElementById('budget').className = "tberror";
		errormessage += "\nBudget field not valid.  Please enter an integer > 0.";
	}

	// check the % complete field is an iteger > 0
	var budget = document.getElementById('percentcomplete').value
	if(!(budget.match('^([0-9]|[1-9][0-9]|100)$'))){
		valid=false;
		document.getElementById('percentcomplete').className = "tberror";
		errormessage += "\nProgress field not valid.  Please enter an integer between 0 and 100.";
	}
	
	if(valid == false){
		alert(errormessage);
		
	}
	return valid;
}
	
	
	</script>
</head>
<body>
	<?php 	include("../inc_files/ui/menu.php");?>

	<table class="datagrid">
		<tr>
			<td class="datagrid headerlabelcell">ProjectID:</td>
			<td class="datagrid headerformcell"><?php echo $projectID;?></td>
		</tr>
		<tr>
			<td class="datagrid headerlabelcell">Title:</td>
			<td class="datagrid headerformcell"><?php echo $projectTitle;?></td>
		</tr>
		<tr>
			<td class="datagrid headerlabelcell">Customer:</td>
			<td class="datagrid headerformcell"><?php echo $customer;?></td>
		</tr>
		<tr>
			<td class="datagrid headerlabelcell">Description:</td>
			<td class="datagrid headerformcell"><?php echo nl2br($descripion);?>
			</td>
		</tr>
		<tr>
			<td class="datagrid headerlabelcell">Project manager:</td>
			<td class="datagrid headerformcell"><?php echo $PMfirstName." ".$PMlastName;?>
			</td>
		</tr>
		<tr>
			<td class="datagrid headerlabelcell">Duration:</td>
			<td class="datagrid headerformcell"><?php echo date('d/m/Y', strtotime($startDate)) ." until ". date('d/m/Y', strtotime($endDate)) ;?>
			</td>
		</tr>
		<tr>
			<td class="separatorrow" colspan="2">Tasks</td>

		</tr>
		<tr>
			<td colspan="2">
				<div id="datagrid"></div>


			</td>

		</tr>
	</table>
	<?php echo "<input type=\"hidden\" id=\"projectid\" name=\"projectid\"  value=\"".$_GET["projectid"]."\">";?>
	<script type="text/javascript">	
	//populate the datagrid on page load
	refreshgrid();	
	</script>
</body>
<?php 	include("../inc_files/ui/footer.php");?>
</html>
